import * as types from './mutation-types'
// import services from '../services'
import * as apis from '../services/apis'
import Vue from 'vue'
import http from '../http'

const appId = 'wx25cc7e5bfd535d83';
const redirect_uri = encodeURI('http://health-shop-app.wlsq.tv/home');

export default {
  wxLogin({
    commit
  }, payload) {
    var tokenStr = localStorage.getItem('token');
    var localToken = JSON.parse(tokenStr);
    // 判断本地是否有token，如果没有，则说明程序处于两种状态之一
    // 1. token刚刚过期，还没去微信获取code
    // 2. 刚从微信获取code回来
    if (tokenStr == null || tokenStr == '' || JSON.parse(tokenStr).expireTime < new Date().getTime()) {
      // 判断链接是否带有code，如果没有code则去微信服务器获取code
      if (payload.code == undefined || payload.code == null) {
        window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + appId + '&redirect_uri=' + redirect_uri + '&response_type=code&scope=snsapi_base&state=0';
        return
      }
    } else {
      commit(types.WXLOGIN, {
        accessToken: localToken.accessToken,
        expireTime: localToken.expireTime
      })
      return
    }

    // 是否有token 或token是否过期
    if (localStorage.getItem('state') == null || localStorage.getItem('state') == '0') {
      payload.state = 1
    } else {
      payload.state = 0
    }
    localStorage.setItem('state', payload.state);
    // Vue.http.post(apis.wxLogin,obj)
    //services.wxLogin.login(obj).
    Vue.http.post(apis.WX_LOGIN, payload).then(res => {
      let status = res.body.status;
      if (status == 1) {
        const data = res.body.result;
        var token = {};
        token.accessToken = data.accessToken;
        token.expireTime = new Date().getTime() + data.expireIn * 1000; // token过期时间
        localStorage.setItem('token', JSON.stringify(token));
        commit(types.WXLOGIN, {
          accessToken: token.accessToken,
          expireTime: token.expireTime
        })
      } else {
        // 登录并且跳到首页
        window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + appId + '&redirect_uri=' + redirect_uri + '&response_type=code&scope=snsapi_userinfo&state=1';
      }
    })
  }
}
